<template lang="pug">
  .page
    .AccountsReceivableManage
      //- .search-form.mb-10.pl-10.pr-10
      //-   Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="120")
      //-     FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
      //-       template(v-if="item.type === 'select'")
      //-         Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
      //-           Option(
      //-             v-for="(c_item, index) in arrListDown[item.options]"
      //-             :value="c_item.value"
      //-             :key="index"
      //-           ) {{ c_item.label }}
      //-       template(v-if="item.type === 'input'")
      //-         Input(v-model="formData[item.model]" :placeholder="item.placeholder")
      //-       template(v-if="item.type === 'interval'")
      //-         DatePicker.pull-left.interval(v-model="formData[item.model1]" :value="datePickerDefault" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker")
      //-         span.pl-10.pr-10.pull-left.line-h-32 --
      //-         DatePicker.pull-left.interval(v-model="formData[item.model2]" :value="datePickerDefault" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker")
      //-       template(v-if="item.type === 'button'")
      //-         Button(v-if="hasFind" type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )
          //- template(slot-scope="{ row, index }" slot="action")
          //-   Button.mr-10(type="text" @click="gotoReceivableBalance(row)") 应收差额查看
          //-   Button.mr-10(type="text" @click="gotoPayableBalance(row)") 应付差额查看
    //- 台账导入弹窗
    ImportStandingBookModal(ref="ImportStandingBookModal" @uploadSuccess="query")

    //- 付款弹窗
    PayModal(ref="PayModal" @query="query")
</template>

<script>
import { FinanceSSPayableApi } from '@/api/FinanceSSPayable.api.js'
import { FinanceCPayableApi } from '@/api/FinanceCPayable.api.js'
import { CommercialChildrenThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import ImportStandingBookModal from './modal/importStandingBookModal.vue'
import PayModal from "../publicModal/payModal.vue"
// import expandRow from './table-expand.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: '',

  components: {
    // expandRow
    ImportStandingBookModal,
    PayModal
  },

  data () {
    return {
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      employeeId: '', // 员工ID
      thead: _cloneDeep(CommercialChildrenThead),
      tableData: [],
      formData: {
        unitName: null,
        commercialNo: '',
        type: '0',
        feeYearMonthStart: new Date(),
        feeYearMonthEnd: new Date(),
        status: null
      },
      formItem: [
        { type: 'input', label: '编号所属单位：', placeholder: '请输入编号所属单位', prop: 'unitName', model: 'unitName', options: 'securityNos', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' },
        { type: 'select', label: '商保编号：', placeholder: '请输入商保编号', prop: 'commercialNo', model: 'commercialNo', options: 'securityNos', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8' },
        { type: 'select', label: '类型：', placeholder: '请输入类型', prop: 'type', model: 'type', options: 'typeArr', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8' },
        { type: 'select', label: '状态：', placeholder: '请输入状态', prop: 'status', model: 'status', options: 'statusOps', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' },
        { type: 'interval', label: '费用月份：', placeholder1: '开始日期', prop1: 'feeYearMonthStart', model1: 'feeYearMonthStart', placeholder2: '结束日期', prop2: 'feeYearMonthEnd', model2: 'feeYearMonthEnd', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6' }
      ],
      rules: {
        IdCardNo: [
          { type: 'string', message: '请输入正确的身份证号码', pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ]
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0, // 应付总计
      },
      downLoadRul: '',
      arrListDown: {
        securityNos: [],
        typeArr: [{ value: '0', label: '全部' }, { value: '1', label: '新增' }, { value: '2', label: '续保' }],
        statusOps: [
          {label: '待申请', value: '1'},
          {label: '已申请', value: '2'},
          {label: '已付款', value: '3'}
        ]
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      }
    }
  },

  watch: {
  },

  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasGetList () {
      return this.actionArr.indexOf('GetList') > -1
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    // 导出实付单-U8
    hasExportPaymentU8 () {
      return this.actionArr.indexOf('ExportPaymentU8') > -1
    },
    // 确认付款
    hasConfirmPay () {
      return this.actionArr.indexOf('ConfirmPay') > -1
    },
    // 个税付款确认
    hasToConfirmPay() {
      return this.actionArr.indexOf("ToConfirmPay") > -1;
    },
    // 申请付款
    hasToPayApply() {
      return this.actionArr.indexOf("ToPayApply") > -1;
    },
    // 应收差额说明
    hasGetBalanceRemarks1() {
      return this.actionArr.indexOf("GetBalanceRemarks1") > -1;
    },
    // 查询
    hasFind() {
      return this.actionArr.indexOf("Find") > -1;
    },
    // 删除
    hasDelete() {
      return this.actionArr.indexOf("Delete") > -1;
    },
    // 应付差额说明
    hasGetBalanceRemarks2() {
      return this.actionArr.indexOf("GetBalanceRemarks2") > -1;
    },
    // 导出
    hasExport() {
      return this.actionArr.indexOf("Export") > -1;
    },
    // 导入
    hasImport() {
      return this.actionArr.indexOf("Import") > -1;
    },
    // 生成付款单
    hasExportPayPDF() {
      return this.actionArr.indexOf("ExportPayPDF") > -1;
    },
    // 导出明细
    hasExportPayableDetail() {
      return this.actionArr.indexOf("ExportPayableDetail") > -1;
    },
    // 导出实付单-U8
    hasExportPaymentU8() {
      return this.actionArr.indexOf("ExportPaymentU8") > -1;
    },
  },
  mounted () {
    this.query()
    this.getSecurityNos()
  },

  methods: {
    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        Year: this.$route.query.year,
        Month: this.$route.query.month,
        SecurityNo: this.$route.query.insureNo,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        CommercialID: this.$route.query.commercialID
      }
      let res = await FinanceCPayableApi.getCPayableBillDetail(params)
      console.log('应付res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows        
        this.tableComone.total = res.data.total
        this.tableData.map(item => {
          item.feeDetails.map(i_item => { // 第一层表格中的数据拼接
            // item[i_item.insuranceCode + 'balance'] = i_item.balance
            item[i_item.insuranceCode + 'should'] = i_item.should
            item[i_item.insuranceCode + 'remark'] = i_item.remark
          })
        })
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 获取保险编号
    async getSecurityNos () {
      var params = {
        type: 3,
        feedate: this.$moment(new Date()).format('YYYY-MM'),
        isall: 1
      }
      let res = await FinanceSSPayableApi.getSecurityNos(params)
      console.log('获取保险编号res: ', res)
      if (res.status === 200 && res.data.success) {
        // this.arrListDown.securityNos = res.data.data
        var arr = []
        res.data.data.map(item => {
          arr.push({value: item.securityNO, label: item.securityNO, companyGUID: item.companyGUID})
        })
        this.arrListDown.securityNos = arr
      } else {
        this.arrListDown.securityNos = []
      }
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择
    handleChangeDatePicker (val) {
      console.log('val: ', val)
      // this.formData.salaryMonth = val
      // this.getDayList()
    },

    // 导出
    async exportCPayableBill () {
      var params = {
        HasPaging: true,
        CommercialNo: this.formData.commercialNo,
        FeeYearMonthStart: this.formData.feeYearMonthStart,
        FeeYearMonthEnd: this.formData.feeYearMonthEnd,
        PageIndex: '',
        PageSize: '',
        Status: this.formData.status,
        UnitName: this.formData.unitName,
      }
      console.log('params: ', params)
      let res = await FinanceCPayableApi.exportCPayableBill(params)
      console.log('导出商保应付账单res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 去往应收差额说明
    gotoReceivableBalance (row) {
      var month = row.periodMonth < 10 ? '0' + row.periodMonth : row.periodMonth
      this.$router.push({
        path: '/financeReceivableBalance',
        name: 'financeReceivableBalance',
        query: {
          insureNo: row.commercialNo,
          month: month,
          year: row.periodYear,
          date: row.periodYear + '-' + month
        }
      })
    },

    // 去往应付差额说明
    gotoPayableBalance (row) {
      var month = row.periodMonth < 10 ? '0' + row.periodMonth : row.periodMonth
      this.$router.push({
        path: '/financePayableBalance',
        name: 'financePayableBalance',
        query: {
          insureNo: row.commercialNo,
          month: month,
          year: row.periodYear,
          date: row.periodYear + '-' + month
        }
      })
    },

    // 去往明细
    gotoDetail (row) {
      var month = row.periodMonth < 10 ? '0' + row.periodMonth : row.periodMonth
      this.$router.push({
        path: '/cPayableDetail',
        name: 'cPayableDetail',
        query: {
          insureNo: row.providentFundNo,
          month: month,
          year: row.periodYear,
          date: row.periodYear + '-' + month
        }
      })
    },

    // 付款-显示弹窗
    handleShowPayModal (row) {
      this.$refs.PayModal.getBankList()
      // this.$refs.PayModal.show()
      this.$refs.PayModal.modalType = 'commercial'
      this.$refs.PayModal.formData.amount = row.total
      Object.keys(this.$refs.PayModal.commercialParams).forEach(key => {
        this.$refs.PayModal.commercialParams[key] = row[key]
      })
      this.$refs.PayModal.checkConfirmPay()
    },
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
